import {
  Directive,
  ElementRef,
  HostListener,
  Inject,
  Input,
  OnInit
} from "@angular/core";

@Directive({
  selector: "[appCode]"
})
export class CodeDirective implements OnInit {
  @Input()
  aim: string;

  @Input()
  type: string;

  defaultVal: string;

  count = 0;

  el: ElementRef;

  readonly from: number = 0;

  readonly to: number = 10;

  timer: any = null;

  pending = false;

  constructor(
    el: ElementRef,
    @Inject("RegService") private regServie,
    @Inject("StoreService") private storeService,
    @Inject("UtilsService") private utilsService,
    @Inject("EmailCodeService") private emailCodeService
  ) {
    this.el = el;
  }

  ngOnInit(): void {}

  isEmptyAim() {
    return !this.aim;
  }

  @HostListener("click")
  async onclick() {
    if (this.pending) {
      return;
    }

    if (this.isEmptyAim()) {
      return;
    }

    if (
      !this.regServie.email.test(this.aim) &&
      !this.regServie.phone.test(this.aim)
    ) {
      return;
    }

    if (this.isCounting()) {
      return;
    }

    this.defaultVal = this.el.nativeElement.innerText;

    this.pending = true;
    this.send().subscribe(res => {
      this.pending = false;
      if (!res || res.code !== 200) {
        // alert(res.msg);
        // console.log(res.msg);
        return;
      }

      this.el.nativeElement.innerText = this.count;

      let onInterval = () => {
        this.el.nativeElement.innerText = this.count;

        if (this.isLimitTo(this.count)) {
          clearInterval(this.timer);
          this.count = this.from;
          this.el.nativeElement.innerText = this.defaultVal;
          onInterval = null;
        }

        ++this.count;
      };

      this.timer = setInterval(onInterval, 1000);
    });
  }

  send() {
    if (this.isEmail(this.aim)) {
      return this.emailCodeService.sendEmailCode({
        email: this.aim,
        type: this.type
      });
    }

    if (this.isPhone(this.aim)) {
      // 这里将来要写成 phone code service
      return this.emailCodeService.sendPhoneCode({
        phone: this.aim,
        type: this.type
      });
    }
  }

  isLimitTo(v) {
    return v === this.to;
  }

  isCounting() {
    const v = +this.el.nativeElement.innerText;
    if (!this.utilsService.isNumber(v)) {
      return false;
    }
    return v >= this.from && v <= this.to;
  }

  isEmail(v) {
    return this.regServie.email.test(v);
  }
  isPhone(v) {
    return this.regServie.phone.test(v);
  }
}
